<?


class User
{
    private $user;
    private $db;
    
    const saltA = 'jf)$hfF$H@UFhfosuf9&$f92ufF($Y&FGs9dfG$(F&FWG(f4ufe9FS(&4fg24oajefbfoufqor2f$IGWYFG$ifuwgf';
    const saltB = 'hjhfihfs0(&#(&#(&!T(&uifsiufhdsfhdusf$@(@*(74878787fdhsufdisuf9$(@&YF$(hfsudfhd(F&$T(&@F$Y';

    public function __construct($db)
    {
        $this->db = $db;
        $this->user = false;
        if (isset($_SESSION['username']))
        {
            $this->authenticate($_SESSION['username'], $_SESSION['password'], true);   
        }
	if (isset($_COOKIE['username']))
	{
	    $this->authenticate($_COOKIE['username'], $_COOKIE['password'], true, true);
	}
    }
    
    public function authenticate($username, $password, $session=false, $cookie=false)
    {
        if (!$session)
        {
            $password = md5(self::saltA.$password.self::saltB);
        }

        $sql = 'SELECT * FROM users WHERE username=:username AND password=:password AND inactive=0';
        $query = $this->db->prepare($sql);
        $query->execute(array('username'=>$username, 'password'=>$password));
        $user = $query->fetchAll(PDO::FETCH_ASSOC);
        
        if (count($user) == 1)
        {
            $this->user = $user[0];
            $_SESSION['username'] = $username;
            $_SESSION['password'] = $password;
            
            if (!$session && !$cookie)
            {
                $sql = 'UPDATE users SET lastlogin=NOW() WHERE ID=:ID';
                $query = $this->db->prepare($sql);
                $query->execute(array('ID'=>$this->user['ID']));
            }
            
            return true;
        }
        return false;
    }
    
    public function logout()
    {
        unset($_SESSION['username']);
		unset($_SESSION['password']);
		setcookie('username', 0, time()-3600);
		setcookie('password', 0, time()-3600);

    }

    public function storeLogin()
    {
        setcookie('username', $_SESSION['username'], time()+60*60*24*30);
		setcookie('password', $_SESSION['password'], time()+60*60*24*30);	
    }
    
    public function getUser($ID)
    {
        if ($ID == $this->user['ID'])
        {
            if ($this->user['code'] == '') $this->user['code'] = $this->genNewCode($this->user['ID']);
            return $this->user;
        }
        else
        {
            $sql = 'SELECT * FROM `users` WHERE `ID`=:ID';
            $query = $this->db->prepare($sql);
            $query->execute(array('ID'=>$ID));
            $found = $query->fetchAll(PDO::FETCH_ASSOC);

            if (count($found) == 1)
            {
                if ($found[0]['code'] == '') {
                    $found[0]['code'] = $this->genNewCode($ID);
                }
                return $found[0];
            }

        }
        return false;
    }

    public function genNewCode($ID)
    {
        $code = md5(rand(1,99999).$ID.rand(1,99999));
        $sql = 'UPDATE `users` SET code=:code WHERE `ID`=:ID';
        $query = $this->db->prepare($sql);
        $query->execute(array('ID'=>$ID, 'code'=>$code));
        return $code;
    }

    public function validateCode($code)
    {
        $sql = 'SELECT * FROM `users` WHERE code=:code';
        $query = $this->db->prepare($sql);
        $query->execute(array(':code'=>$code));
        $users = $query->fetchAll(PDO::FETCH_ASSOC);
        return count($users) > 0;
    }
    
    public function getAllUsers($inactive=0)
    {
        $sql = 'SELECT * FROM `users` WHERE inactive=:inactive ORDER BY lastname';
        $query = $this->db->prepare($sql);
        $query->execute(array(':inactive'=>$inactive));
        $users = $query->fetchAll(PDO::FETCH_ASSOC);
        return $users;
    }
    
    public function addUser($u)
    {
        if (trim($u['username']) == '')
        {
            return 'Username cannot be blank.';
        }   
        $sql = 'SELECT * FROM users WHERE username=:username';
        $query = $this->db->prepare($sql);
        $query->execute(array(':username'=>$u['username']));
        $exists = $query->fetchAll(PDO::FETCH_ASSOC);
        if (count($exists) > 0)
        {
            return 'Username already exists.';
        }
        $sql = 'INSERT INTO `users` SET username=:username, firstname=:firstname, lastname=:lastname, email=:email, password=:password';
        $query = $this->db->prepare($sql);
        $query->execute(array(':username'=>$u['username'], 
                              ':firstname'=>$u['firstname'], 
                              ':lastname'=>$u['lastname'], 
                              ':email'=>$u['email'],
                              ':password'=>$this->genPassword($u['password'])));
        return true;
    }
    
    private function genPassword($p)
    {
        return md5(self::saltA.$p.self::saltB);
    }
    
    public function updateUser($ID, $fields)
    {
        if (isset($_POST['gen_new_code'])) {
            $this->genNewCode($ID);
        }
        $sql = 'UPDATE users SET username=:username, firstname=:firstname, lastname=:lastname, email=:email WHERE ID=:ID';
        $query = $this->db->prepare($sql);
        $query->execute(array('username'=>$fields['username'],'firstname'=>$fields['firstname'], 'lastname'=>$fields['lastname'], 'email'=>$fields['email'], 'ID'=>$ID));
        if ($ID == $this->user['ID'])
        {
            $_SESSION['username'] = $fields['username'];
            $sql = 'SELECT * FROM users WHERE ID=:ID';
            $query = $this->db->prepare($sql);
            $query->execute(array('ID'=>$ID));
            $this->user = $query->fetch(PDO::FETCH_ASSOC);
        }
    }
    
    public function updatePassword($ID, $password)
    {
        $password = md5(self::saltA.$password.self::saltB);
        $sql = 'UPDATE users SET password=:password WHERE ID=:ID';
        $query = $this->db->prepare($sql);
        $query->execute(array('password'=>$password, 'ID'=>$ID));
        if ($ID == $this->user['ID'])
        {
            $_SESSION['password'] = $password;
            $this->user['password'] = $password;
        }
    }
    
    public function getUsername($ID='')
    {
        if ($ID == '' || $ID == $this->user['ID'])
        {
            return $this->user['username'];
        }
        else
        {
            $user = $this->getUser($ID);
            return $user['username'];
        }
    }
    
    public function getFullname($ID)
    {
        if ($ID == '' || $ID == $this->user['ID'])
        {
            return $this->user['firstname'].' '.$this->user['lastname'];
        }
        else
        {
            $user = $this->getUser($ID);
            return $user['firstname'].' '.$user['lastname'];
        }
    }
    
    public function getAdministrators()
    {
        $sql = 'SELECT * FROM users WHERE admin=:admin';
        $query = $this->db->prepare($sql);
        $query->execute(array('admin'=>1));
        $admins = $query->fetchAll(PDO::FETCH_ASSOC);
        return $admins;
    }
    
    public function getID()
    {
        return $this->user['ID'];
    }
    
    public function loggedIn()
    {
        return is_array($this->user);
    }
    
    public function isAdmin()
    {
        return ($this->user['admin'] == 1);
    }

}

?>
